<?php

namespace yunj\app\admin\validate\member;

use yunj\app\admin\enum\State;
use yunj\app\admin\enum\TableBuilderEvent;
use yunj\app\admin\validate\Validate;

class MemberValidate extends Validate {

    protected function handleData(array &$data, $scene): void {
        switch ($scene) {
            case 'MemberListEvent':
                $this->handleDataByMemberListEvent($data);
                break;
            case 'MemberFormSubmit':
                $this->handleDataByMemberFormSubmit($data);
                break;
            case 'MemberProfileSubmit':
                $this->handleDataByMemberProfileSubmit($data);
                break;
        }
    }

    private function handleDataByMemberListEvent(&$data): void {
        $event = $data['event'];
        $ids = $data['ids'];
        // 超管账户不可移入回收站或者删除
        if ($event == TableBuilderEvent::DELETED || $event == TableBuilderEvent::RECYLE_BIN) {
            /** @var TableBuilderEvent $eventObj */
            $eventObj = TableBuilderEvent::byValue($event);
            $adminData = self::getAdminMemberModel()->getOwnRowToArray([
                ['pid', '=', 0],
            ]);
            if (!$adminData) throw_error_json('初始超管账户异常');
            if (in_array($adminData['id'], $ids)) {
                throw_error_json('初始超管账户不可' . $eventObj->getDesc());
            }
        }
    }

    private function handleDataByMemberFormSubmit(&$data): void {
        $id = $data['id'] ?? 0;

        $currTime = time();
        $dbMemberData = [
            'name' => $data['name'],
            'last_update_time' => $currTime,
        ];

        if ($id) {
            // 编辑
            // 判断编辑数据是否存在
            $memberData = self::getAdminMemberModel()->getOwnRowToArray([
                ['id', '=', $id],
                ['state', '<>', State::DELETED]
            ]);
            if (!$memberData) throw_error_json('数据异常，请刷新页面后重试');
            $data['rawMemberData'] = $memberData;
            $dbMemberData['id'] = $id;
        }else{
            // 添加
            $dbMemberData += [
                'pid' => $this->getMemberId(),
                'create_time' => $currTime,
            ];
        }

        // 账户
        if (isset($data['username'])) {
            $username = $data['username'];
            $where = [
                ['username', '=', $username]
            ];
            if ($id) $where[] = ['id', '<>', $id];
            $hasExist = self::getAdminMemberModel()->getOwnCount($where);
            if ($hasExist) throw_error_json('账户[' . $username . ']已存在');
            $dbMemberData['username'] = $username;
        }
        // 密码
        if(isset($data['password'])){
            if(!$id){
                // 添加
                $data['password'] = $data['password'] ?: '123456';
            }
            if ($data['password']) {
                [$passwordHash, $passwordSalt] = password_handle($data['password']);
                $dbMemberData += [
                    'password_salt' => $passwordSalt,
                    'password_hash' => $passwordHash,
                ];
            }
        }
        // 角色
        if(isset($data['role_ids'])){
            if($id){
                // 编辑
                $memberRoleIds = self::getAdminMemberRoleRelationModel()->getColumnOptions('role_id', [['member_id', '=', $id]]);
                // 初始超管角色不能编辑（判断是否存在差集）
                if ($memberData['pid'] == 0 && array_merge(array_diff($data['role_ids'], $memberRoleIds), array_diff($memberRoleIds, $data['role_ids']))) {
                    throw_error_json('初始超管角色不允许修改');
                }
                if($memberData['pid'] != 0){
                    $dbMemberRoleIds = $data['role_ids'];
                }
            }else{
                // 添加
                $dbMemberRoleIds = $data['role_ids'];
            }
        }

        $data['dbMemberData'] = $dbMemberData;
        $data['dbMemberRoleIds'] = $dbMemberRoleIds ?? null;
    }

    private function handleDataByMemberProfileSubmit(&$data): void {
        $member = $this->getMember();
        $id = $member->id;
        // 判断username是否存在
        $username = $data['username'];
        $where = [
            ['username', '=', $username]
        ];
        if ($id) $where[] = ['id', '<>', $id];
        $hasExist = self::getAdminMemberModel()->getOwnCount($where);
        if ($hasExist) throw_error_json('账户[' . $username . ']已存在');

        $currTime = time();
        $dbMemberData = [
            'id' => $id,
            'name' => $data['name'],
            'username' => $data['username'],
            'last_update_time' => $currTime,
        ];
        if ($data['password']) {
            [$passwordHash, $passwordSalt] = password_handle($data['password']);
            $dbMemberData += [
                'password_salt' => $passwordSalt,
                'password_hash' => $passwordHash,
            ];
        }

        $data['dbMemberData'] = $dbMemberData;
    }

}